#!/bin/sh
#
# Kopano Konnect Daemon (konnectd) launcher
#
# License: Apache-2.0
# Copyright 2018 Kopano and its licensors
#

set -e

# Base defines.

EXE=/usr/libexec/kopano/konnectd
OPENSSL=openssl
DEFAULT_IDENTIY_MANAGER=kc
DEFAULT_WEB_RESOURCES_PATH=/usr/share/kopano-konnect
DEFAULT_IDENTIFIER_REGISTRATION_FILE=/etc/kopano/konnectd-identifier-registration.yaml
DEFAULT_IDENTIFIER_SCOPES_FILE=/etc/kopano/konnectd-identifier-scopes.yaml
DEFAULT_OIDC_ISSUER_IDENTIFIER=https://localhost
DEFAULT_SIGNING_PRIVATE_KEY_FILE=/etc/kopano/konnectd-signing-private-key.pem
DEFAULT_VALIDATION_KEYS_PATH=/etc/kopano/konnectkeys
DEFAULT_ENCRYPTION_SECRET_KEY_FILE=/etc/kopano/konnectd-encryption-secret.key
DEFAULT_KOPANO_SERVER_URI=file:///run/kopano/server.sock

# Handle parameters for configuration.

case "${1}" in
	setup)

	if [ -z "$signing_private_key" -a ! -e "${DEFAULT_SIGNING_PRIVATE_KEY_FILE}" -a -n "$USER" ]; then
		if [ -z "$signing_method" -o "$signing_method" = "PS256" -o "$signing_method" = "RS256" ]; then
			mkdir -p "${DEFAULT_VALIDATION_KEYS_PATH}" && chown "$USER" "${DEFAULT_VALIDATION_KEYS_PATH}"
			rnd=$(RANDFILE=/tmp/.rnd $OPENSSL rand -hex 2)
			key="${DEFAULT_VALIDATION_KEYS_PATH}/konnect-$(date +%Y%m%d)-${rnd}.pem"
			>&2	echo "setup: creating new RSA private key at ${key} ..."
			RANDFILE=/tmp/.rnd $OPENSSL genpkey -algorithm RSA -out "${key}" -pkeyopt rsa_keygen_bits:4096 -pkeyopt rsa_keygen_pubexp:65537 && chown "$USER" "${key}" || true
			if [ -f "${key}" ]; then
				ln -sn "${key}" "${DEFAULT_SIGNING_PRIVATE_KEY_FILE}" || true
			fi
		fi
	fi

	if [ -z "$encryption_secret_key" -a ! -f "${DEFAULT_ENCRYPTION_SECRET_KEY_FILE}" -a -n "$USER" ]; then
		>&2	echo "setup: creating new secret key at ${DEFAULT_ENCRYPTION_SECRET_KEY_FILE} ..."
		RANDFILE=/tmp/.rnd $OPENSSL rand -out "${DEFAULT_ENCRYPTION_SECRET_KEY_FILE}" 32 && chown "$USER" "${DEFAULT_ENCRYPTION_SECRET_KEY_FILE}" || true
	fi

	# Setup subcommand does nothing.
	exit 0

	;;

	serve)
		# Inject values from environment into command line. This is mainly used
		# when this script is run from systemd or docker.

		shift

		# konnectd basics

		if [ -z "$identity_manager" ]; then
			identity_manager="${DEFAULT_IDENTIY_MANAGER}"
		fi

		if [ -z "$web_resources_path" ]; then
			web_resources_path="${DEFAULT_WEB_RESOURCES_PATH}"
		fi

		if [ -z "$identifier_registration_conf" ]; then
			if [ -f "${DEFAULT_IDENTIFIER_REGISTRATION_FILE}" ]; then
				identifier_registration_conf="${DEFAULT_IDENTIFIER_REGISTRATION_FILE}"
			fi
		fi

		if [ -z "$identifier_scopes_conf" ]; then
			if [ -f "${DEFAULT_IDENTIFIER_SCOPES_FILE}" ]; then
				identifier_scopes_conf="${DEFAULT_IDENTIFIER_SCOPES_FILE}"
			fi
		fi

		if [ -n "$oidc_issuer_identifier" ]; then
			if [ -n "$OIDC_ISSUER_IDENTIFIER" ]; then
				>&2	echo "Warning: duplicate setting of issuer identifier - using value from environment"
				oidc_issuer_identifier="$OIDC_ISSUER_IDENTIFIER"
			fi
		fi
		if [ -z "$oidc_issuer_identifier" ]; then
			# NOTE(longsleep): Not sure if this is the best idea/default but at least
			# having a default will let the service start.
			oidc_issuer_identifier=${OIDC_ISSUER_IDENTIFIER:-${DEFAULT_OIDC_ISSUER_IDENTIFIER}}
		fi

		if [ "$insecure" = "yes" ]; then
			set -- "$@" --insecure
		fi

		if [ -n "$listen" ]; then
			set -- "$@" --listen="$listen"
		fi

		if [ -n "$log_level" ]; then
			set -- "$@" --log-level="$log_level"
		fi

		if [ -n "$allowed_scopes" ]; then
			for scope in $allowed_scopes; do
				set -- "$@" --allow-scope="$scope"
			done
		fi

		if [ -n "$identifier_scopes_conf" ]; then
			set -- "$@" --identifier-scopes-conf="$identifier_scopes_conf"
		fi

		if [ -z "$signing_private_key" -a -f "${DEFAULT_SIGNING_PRIVATE_KEY_FILE}" ]; then
			signing_private_key="${DEFAULT_SIGNING_PRIVATE_KEY_FILE}"
		fi
		if [ -n "$signing_private_key" ]; then
			set -- "$@" --signing-private-key="$signing_private_key"
		fi

		if [ -n "$signing_kid" ]; then
			set -- "$@" --signing-kid="$signing_kid"
		fi

		if [ -n "$signing_method" ]; then
			set -- "$@" --signing-method="$signing_method"
		fi

		if [ -z "$validation_keys_path" -a -d "${DEFAULT_VALIDATION_KEYS_PATH}" ]; then
			validation_keys_path="${DEFAULT_VALIDATION_KEYS_PATH}"
		fi
		if [ -n "$validation_keys_path" ]; then
			set -- "$@" --validation-keys-path="$validation_keys_path"
		fi

		if [ -z "$encryption_secret_key" -a -f "${DEFAULT_ENCRYPTION_SECRET_KEY_FILE}" ]; then
			encryption_secret_key="${DEFAULT_ENCRYPTION_SECRET_KEY_FILE}"
		fi
		if [ -n "$encryption_secret_key" ]; then
			set -- "$@" --encryption-secret="$encryption_secret_key"
		fi

		if [ -n "$trused_proxies" ]; then
			for proxy in $trusted_proxies; do
				set -- "$@" --trusted-proxy="$proxy"
			done
		fi

		if [ "$allow_client_guests" = "yes" ]; then
			set -- "$@" --allow-client-guests
		fi

		if [ "$allow_dynamic_client_registration" = "yes" ]; then
			set -- "$@" --allow-dynamic-client-registration
		fi

		if [ -n "$access_token_expiration" ]; then
			set -- "$@" --access-token-expiration="$access_token_expiration"
		fi

		if [ -n "$id_token_expiration" ]; then
			set -- "$@" --id-token-expiration="$id_token_expiration"
		fi

		if [ -n "$refresh_token_expiration" ]; then
			set -- "$@" --refresh-token-expiration="$refresh_token_expiration"
		fi

		if [ -n "${uri_base_path:-}" ]; then
			set -- "$@" --uri-base-path="$uri_base_path"
		fi

		# kc identity manager

		if [ "$identity_manager" = "kc" ]; then
			if [ -z "$kc_server_uri" ]; then
				kc_server_uri=${KOPANO_SERVER_DEFAULT_URI:-${DEFAULT_KOPANO_SERVER_URI}}
			fi
			export KOPANO_SERVER_DEFAULT_URI="$kc_server_uri"

			if [ -z "$kc_session_timeout" ]; then
				export KOPANO_SERVER_SESSION_TIMEOUT="$kc_session_timeout"
			fi
		fi

		# ldap identity manager
		if [ "$identity_manager" = "ldap" ]; then
			if [ -n "$ldap_uri" ]; then
				export LDAP_URI="$ldap_uri"
			fi
			if [ -n "$ldap_binddn" ]; then
				export LDAP_BINDDN="$ldap_binddn"
			fi
			if [ -n "$ldap_bindpw" ]; then
				export LDAP_BINDPW="$ldap_bindpw"
			fi
			if [ -n "$ldap_basedn" ]; then
				export LDAP_BASEDN="$ldap_basedn"
			fi
			if [ -n "$ldap_scope" ]; then
				export LDAP_SCOPE="$ldap_scope"
			fi
			if [ -n "$ldap_login_attribute" ]; then
				export LDAP_LOGIN_ATTRIBUTE="$ldap_login_attribute"
			fi
			if [ -n "$ldap_uuid_attribute" ]; then
				export LDAP_UUID_ATTRIBUTE="$ldap_uuid_attribute"
			fi
			if [ -n "$ldap_filter" ]; then
				export LDAP_FILTER="$ldap_filter"
			fi
		fi

		# set identity manager at the end

		set -- serve --identifier-client-path="$web_resources_path/identifier-webapp" --identifier-registration-conf="$identifier_registration_conf" --iss="$oidc_issuer_identifier" "$@" "$identity_manager" $identity_manager_args

		;;

	*)
		;;
esac

# Set executable.

set -- ${EXE} "$@"

# Run.

exec "$@"
